package orm.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;
import orm.base.Ex.BaseEx;
import wangchao.tools.PostOrGet;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * 微信Utils
 * Created by ashin on 2017/8/15.
 */
@Component
public class WxUtils extends BaseEx {

    //微信appId
    private final static String appId = "wx5242795968d26d9d";

    //微信secrect
    private final static String appSecret = "e58239fbe60a079718cc1174871c3d5f";

    //获得access_token的地址
    private static String getAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";

    //授权URL
    private static String oauth_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=STATE#wechat_redirect";

    //获得用户openId地址
    private static String wx_openId_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";

    //获取微信用户信息
    private static String wx_user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN";

    //根据access_token获得ticket
    private static String wx_ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi";

    //微信发送消息模板接口
    private static String wx_template_send_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s";

    //获取access_token的时间
    private static Date accessTokenTime = new Date();

    //获得tikcet的时间
    private static Date ticketTime = new Date();

    //借款进度模板
    public static String shenqingjindu = "FAlrPfNqYKwwshjIVLaUEvJEa-qGk6VHnGwGnDKoqkY";
    /**
     * 微信授权页面
     *
     * @param redirectUri
     * @return
     */
    public String redirectWxOauth(String redirectUri) {
        return String.format(oauth_url, appId, redirectUri, "snsapi_userinfo");
    }

    /**
     * 发送微信模板消息
     * @param params 发送参数
     * @return
     * @throws Exception
     */
    public JSONObject sendTemplate(String params) throws Exception{
        JSONObject accessTokenJSON = getAccessToken();
        if (accessTokenJSON.getInteger("code") == eCode)
            return accessTokenJSON;
        else {
            String accessToken = accessTokenJSON.getString("data");
            String result = PostOrGet.sendPost(String.format(wx_template_send_url,accessToken),params,null);
            logger.info(result);
            return this.codeData(JSON.parseObject(result));
        }
    }

    /**
     * 获得微信OpenId
     *
     * @return
     * @throws Exception
     */
    public JSONObject getWxOpenId(String code) throws Exception {
        String url = String.format(wx_openId_url, appId, appSecret, code);
        String openIdStr = PostOrGet.sendGet(url);
        JSONObject openIdJSON = JSON.parseObject(openIdStr);
        if (openIdJSON.getString("errcode") != null) {
            return this.codeData(eCode, openIdJSON.getString("errmsg"));
        } else {
            return openIdJSON;
        }
    }

    public JSONObject getWxTicket() throws Exception {
        String wxTicket = redisService.get("wx_ticket");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(ticketTime);
        calendar.add(Calendar.MINUTE, 90);
        if (wxTicket == null || calendar.compareTo(Calendar.getInstance()) <= 0) {
            JSONObject accessTokenJSON = getAccessToken();
            if (accessTokenJSON.getInteger("code") == eCode)
                return accessTokenJSON;
            else {
                String accessToken = accessTokenJSON.getString("data");
                String ticketStr = PostOrGet.sendGet(String.format(wx_ticket_url, accessToken));
                JSONObject ticketJSON = JSON.parseObject(ticketStr);
                String ticket = ticketJSON.getString("ticket");
                redisService.set("wx_ticket", ticket);
                ticketTime = new Date();
                return this.codeData(sCode, ticket);
            }
        } else {
            return codeData(sCode, wxTicket);
        }
    }

    /**
     * 获得微信用户信息
     *
     * @return
     * @throws Exception
     */
    public JSONObject getWxUserInfo(String code) throws Exception {
        JSONObject openIdJSON = getWxOpenId(code);
        if (openIdJSON.get("code") != null)
            return this.codeData(eCode, openIdJSON.getString("data"));
        else {
            String userInfoStr = PostOrGet.sendGet(String.format(wx_user_info_url, openIdJSON.getString("access_token"), openIdJSON.getString("openid")));
            JSONObject userInfoJSON = JSON.parseObject(userInfoStr);
            if (userInfoJSON.getString("errcode") != null) {
                return this.codeData(eCode, userInfoJSON.getString("errmsg"));
            }
            return this.codeData(sCode, userInfoJSON);
        }
    }

    /**
     * 获得accessToken
     *
     * @return
     * @throws Exception
     */
    public JSONObject getAccessToken() throws Exception {
        String accessToken = redisService.get("wx_access_token");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(accessTokenTime);
        calendar.add(Calendar.MINUTE, 90);
        //如果redis里面的accessToken不存在或者上一次获取的accessToken时间小于或者等于当前时间
        if (accessToken == null || calendar.compareTo(Calendar.getInstance()) <= 0) {
            //重新获取accessToken
            String accessTokenStr = PostOrGet.sendGet(String.format(getAccessTokenUrl, appId, appSecret));
            JSONObject accessTokenJSON = JSONObject.parseObject(accessTokenStr);
            String errorcode = accessTokenJSON.getString("errcode");
            if (errorcode == null) {
                accessToken = accessTokenJSON.getString("access_token");
                redisService.set("wx_access_token", accessToken);
                accessTokenTime = new Date();
                return codeData(sCode, accessToken);
            } else {
                return codeData(eCode, accessTokenJSON.getString("errmsg"));
            }
        } else {
            return codeData(sCode, accessToken);
        }
    }

    public Map<String, String> sign(String url) throws Exception {
        String jsapi_ticket = getWxTicket().getString("data");
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";

        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + url;
        System.out.println(string1);

        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);
        ret.put("appId",appId);
        return ret;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
}
